package cn.jiyun.controller;

import cn.hutool.jwt.JWTUtil;
import cn.jiyun.feign.TestService;
import cn.jiyun.pojoday14.Emp;
import cn.jiyun.utils.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 小周
 * @Package: cn.jiyun.controller
 * @Project: 2210A-project1
 * @name: UserController
 * @Date: 2023/8/22 19:42
 * @Filename: UserController
 */
@RestController
@RequestMapping("day01user")
public class UserController {
    @Autowired
    private TestService testService;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("login")
    public Result login(@RequestBody Emp emp){
        try {
            Emp one = testService.toLogin(emp);
            if (one!=null){
                //生成token
                Map map=new HashMap();
                map.put("Userid",one.getEid());
                String token = JWTUtil.createToken(map, "zhou".getBytes());
                //存到redis中
                redisTemplate.opsForValue().set(token, JSONObject.toJSONString(one),30, TimeUnit.MINUTES);
                return Result.ok().data("token",token);
            }else{
                return Result.error().message("用户名或密码错误");
            }
        }catch (Exception e){
         e.printStackTrace();
         return Result.error();
        }
    }


}
